<?php

namespace App\Http\Controllers\Laifei\Orders;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiOrdersStoreController extends Controller
{

    public function index()
    {

        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 20;
        $pageNo = $all['pageNo'] ?? 1;

        try {

            $where = function ($query) use ($all) {
                $query->where('lo.status', '=', 1);
                if(isset($all['openid'])){
                    $query->where('lu.openid','=',$all['openid']);
                }
                if(isset($all['trade_no'])){
                    $query->where('lo.trade_no','=',$all['trade_no']);
                }
                if(isset($all['type']) && count($all['type'])){
                    $query->whereIn('lo.type', $all['type']);
                }
                if(isset($all['nickname'])){
                    $query->where('lu.nickname','like','%'.$all['nickname'].'%');
                }
                if(isset($all['phone'])){
                    $query->where('lu.phone','=',$all['phone']);
                }
                if(isset($all['time']) && count($all['time']) === 2){
                    $query->whereBetween('lo.success_at',$all['time']);
                }
                if(isset($all['course_id']) && count($all['course_id'])){
                    $query->where('lo.type','=',2)
                        ->whereIn('lo.outer_id',$all['course_id']);
                }
                if(isset($all['vip_id']) && count($all['vip_id'])){
                    $query->where('lo.type','=',1)
                        ->whereIn('lo.outer_id',$all['vip_id']);
                }
            };

            $total = DB::table('laifei_orders as lo')
                ->leftJoin('lottery_users as lu', 'lo.we_id', '=', 'lu.we_id')
                ->where($where)
                ->count();

            // 查询订单信息
            $info = DB::table('laifei_orders as lo')
                ->leftJoin('lottery_users as lu', 'lo.we_id', '=', 'lu.we_id')
                ->orderByDesc('lo.order_id')
                ->where($where)
                ->select('lo.order_id', 'lo.we_id', 'lo.trade_no', 'lo.type', 'lo.outer_id', 'lo.vc_id', 'lo.total_fee', 'lo.success_at as pay_success_time', 'lo.created_at as create_order_time',
                    'lo.start_date','lo.end_date','lo.num',
                    'lu.openid', 'lu.nickname', 'lu.phone')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->get();

            // 查询vip和课程信息
            $vip_messages = DB::table('laifei_sys_vip')
                ->select('vip_id', 'title', 'subtitle')
                ->get()
                ->keyBy('vip_id')
                ->toArray();
            $vip_messages = json_decode(json_encode($vip_messages), true);
            $course_messages = DB::table('laifei_sys_course')
                ->select('course_id', 'title', 'subtitle')
                ->get()
                ->keyBy('course_id')
                ->toArray();
            $course_messages = json_decode(json_encode($course_messages), true);

            // 查询vip订单和课程订单信息
            $vip_orders = $info->where('type', '=', 1)->pluck('vc_id');
//            $course_orders = $info->where('type', '=', 2)->pluck('vc_id');

            $vip_orders = DB::table('laifei_vip')
                ->whereIn('v_id', $vip_orders)
                ->get()
                ->keyBy('v_id')
                ->toArray();
            $vip_orders = json_decode(json_encode($vip_orders), true);
//            $course_orders = DB::table('laifei_course')
//                ->whereIn('c_id', $course_orders)
//                ->get()
//                ->keyBy('c_id')
//                ->toArray();
//            $course_orders = json_decode(json_encode($course_orders), true);


            // 查询探店渠道
            $channels = DB::table('explore_channel')
                ->select('channel_id','channel_name')
                ->get()
                ->mapWithKeys(function($item){
                    return [$item->channel_id => $item->channel_name];
                })
                ->toArray();

            $info = $info->toArray();
            $info = json_decode(json_encode($info), true);

            foreach ($info as $key => $value) {
                if ($value['type'] === 1) { // vip
                    $info[$key]['title']      = $vip_messages[$value['outer_id']]['title'];
                    $info[$key]['subtitle']   = $vip_messages[$value['outer_id']]['subtitle'];
                    // 根据当前vip_id的会员是否到期，判定是否有效
                    $info[$key]['status']     = strtotime($vip_orders[$value['vc_id']]['end_time']) > time();
                    $info[$key]['status_str'] = $info[$key]['status']? '有效': '无效';
                } elseif ($value['type'] === 2) { // 课程
                    $info[$key]['title']      = $course_messages[$value['outer_id']]['title'];
                    $info[$key]['subtitle']   = $course_messages[$value['outer_id']]['subtitle'];
                    $info[$key]['end_date']     = '-';
                    $info[$key]['status']     = true;
                    $info[$key]['status_str'] = '有效';
                } elseif($value['type'] === 3) {
                    $info[$key]['title']      = '达人探店';
                    $info[$key]['subtitle']   = $channels[$value['outer_id']].'  【'.$info[$key]['num'].'】次';
                    $info[$key]['start_date']     = '-';
                    $info[$key]['end_date']     = '-';
                    $info[$key]['status']     = true;
                    $info[$key]['status_str'] = '-';
                } elseif($value['type'] === 4) {
                    $info[$key]['title']      = '霸王餐';
                    $info[$key]['subtitle']   = '【'.$info[$key]['num'].'】次';
                    $info[$key]['start_date']     = '-';
                    $info[$key]['end_date']     = '-';
                    $info[$key]['status']     = true;
                    $info[$key]['status_str'] = '-';
                }
            }

            return $this->setReturnJson(0,'success',['total'=>$total,'info'=>$info]);
        } catch (\Exception $e) {
            Log::error(LaifeiOrdersStoreController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'查询失败');
        }
    }

}
